package il.technion.cs236369.webserver;

import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.impl.DefaultHttpServerConnection;

/**
 * The request object that is being put in the requests queue
 * @author Yuval and Eddie
 *
 */
public class Request {
	private WebServer webServer;					// The web server 
	private DefaultHttpServerConnection conn;		// Connection to client

	// Request contents
	private String method;					// GET or POST etc...
	private String absolutePath;			// This is the absolute path in the server's file system
	private HashMap<String,String> params;	// URL parameter name, parameter value
	private HttpEntity entity;				// body of POST requests
	private Header[] headers;
	
	public Request(WebServer webServer, DefaultHttpServerConnection conn, String method,
			String absolutePath, HttpEntity entity, Header[] headers) {
		super();
		this.webServer = webServer;
		this.conn = conn;
		this.method = method;
		this.absolutePath = absolutePath;
		this.entity = entity;
		this.headers = headers;
		this.params = new HashMap<String,String>(); 
		if (absolutePath.equals(webServer.getBaseDir())) {
			setPathToWelcomeFile();
		}
	}

	/**
	 * 
	 * @return absolute path in the server's file system to the request file
	 */
	public String getAbsolutePath() {
		return absolutePath;
	}

	public String getRequestExtension() {
		int extentionIndex = absolutePath.lastIndexOf(".");
		return absolutePath.substring(extentionIndex+1);
	}

	/**
	 * 
	 * @return the type of the request, i.e. "GET" or "POST"
	 */
	public String getMethod() {
		return method;
	}
	
	public DefaultHttpServerConnection getConnection() {
		return conn;
	}

	public HttpEntity getEntity() {
		return entity;
	}

	public void setEntity(HttpEntity entity) {
		this.entity = entity;
	}

	public void setPathToWelcomeFile(){
		absolutePath = webServer.getBaseDir() + webServer.getWelcomeFile();
	}
	
	/**
	 * Inserts a parameter to the map. If the parameter already exists- updates it to the new value.
	 * @param paramName - name of parameter
	 * @param paramVal - new value of parameter
	 */
	public void insertParameter(String paramName, String paramVal){
		params.put(paramName, paramVal);
	}

	/**
	 * Returns the value of a parameter
	 * @param paramName - the name of the parameter
	 * @return - parameter value (string), or null if paramName is not a parameter
	 */
	public String getParam(String paramName) {
		return params.get(paramName);
	}
	
	public Header[] getHeaders() {
		return headers;
	}

	public WebServer getWebServer() {
		return webServer;
	}
	
	public HashMap<String,String> getParamsMap() {
		return params;
	}
}
